package com.qf.mp2301.controller;

import com.qf.mp2301.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Map;

@RestController
@RequestMapping("/homework")
@Slf4j
public class HomeworkController {

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/do")
    public R doHomeWork(String name){

        // 准备key
        String key = "homework:doHomeWork";

        // 写入Redis
        redisTemplate.opsForHash().increment(key,name,1);

        return R.ok();
    }

    @GetMapping("/check")
    public R checkHomeWork(String name){
        // 准备key
        String key = "homework:doHomeWork";

        // 获取 hash结构中指定field的内容
        Object o = redisTemplate.opsForHash().get(key, name);
//        Map entries = redisTemplate.opsForHash().entries(key);
//        log.info("所有的数据为={}",entries);

        log.info("{}同学一共交了{}次作业",name,o);

        return R.ok(o);
    }

    /**
     * 从redis中查询所有同学的交作业情况，按照次数从高到底排序
     * @return
     */
    @GetMapping("/checkall")
    public R checkAll(){

        // 获取redis hash中的全部数据
        String key = "homework:doHomeWork";
        Map map = redisTemplate.opsForHash().entries(key);
        log.info("所有的数据为={}",map);

        // 把map中的所有 entry对象放入一个list中
        ArrayList<Map.Entry<String, Integer>> list
                = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());

        // list 排序
        list.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        return R.ok(list);
    }

}
